package utils

import (
	"database/sql"
	"encoding/xml"
	"fmt"
	"io/ioutil"

	_ "github.com/go-sql-driver/mysql"
)

type mysqlcf struct {
	Conf conf `xml:"config"`
}

type conf struct {
	Server   string `xml:"server,attr"`
	Port     string `xml:"port,attr"`
	User     string `xml:"user,attr"`
	Pwd      string `xml:"pwd,attr"`
	Database string `xml:"database,attr"`
}

var Db *sql.DB

// mysql数据库连接
func init() {
	data, _ := ioutil.ReadFile("mysql.xml")
	var s mysqlcf
	xml.Unmarshal(data, &s)
	conf := s.Conf
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=true", conf.User, conf.Pwd, conf.Server, conf.Port, conf.Database)
	t, err := sql.Open("mysql", dsn)
	err = t.Ping()
	if err != nil {
		panic(err)
	}
	Db = t
	Db.SetMaxOpenConns(100)
	Db.SetMaxIdleConns(50)
}

func CloseMySQL() {
	if Db != nil {
		fmt.Println("断开MYSQL数据库连接!")
		Db.Close()
	}
}
